import { Component } from '@angular/core';
import {IonicPage, NavController, NavParams, Platform} from 'ionic-angular';
import {SourceViewProvider} from "../../providers/source-view/source-view";
import {ThemeableBrowserObject} from "@ionic-native/themeable-browser";
import {ApiProvider} from "../../providers/api/api";
import {UnitSourceListPage} from "../unit-source-list/unit-source-list";

/**
 * Generated class for the ViewSourcePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-view-source',
  templateUrl: 'view-source.html',
})
export class ViewSourcePage {

  path;
  title;
  type;
  backTime;
  inTime;
  studentId;
  source_idStr;

  themeableBrowser:ThemeableBrowserObject;
  constructor(public navCtrl: NavController, public navParams: NavParams,public souceview:SourceViewProvider,public http:ApiProvider,public platform:Platform) {
    this.platform.ready().then(() => {
      this.platform.registerBackButtonAction(() => {
        alert("返回");
        //this.navCtrl.push(UnitSourceListPage,{classCourseId:this.classCourseId,teacherId:this.teacherId,unitId:unitId,studentId:this.studentId});
      });
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ViewSourcePage');
  }

  ionViewDidEnter()
  {
    this.inTime=Date.parse(new Date().toString());
    this.path=this.navParams.get("path");
    this.title=this.navParams.get("title");
    this.type=this.navParams.get("type");
    this.studentId=this.navParams.get("studentId");
    this.source_idStr=this.navParams.get("source_idStr");

    //案例、链接、图片
    if(this.type=="40002"||this.type=="40003"||this.type=="40010")
    {
      //alert("打开"+this.type);
      this.themeableBrowser=this.souceview.showPage(this.path,this.title);
    }
    //视频
    else if(this.type=="40009")
    {
      //alert("打开"+this.type);
      this.souceview.showVideo(this.path);
    }
    //讲义、PDF
    else if(this.type=="40005"||this.type=="40011")
    {
      //alert("打开"+this.type);
      this.souceview.openFile(this.path);
    }

    //后退更新查看时长
    this.themeableBrowser.on("backPressed").subscribe(item=>{
      this.backTime=Date.parse(new Date().toString());
      let look_time=(this.backTime-this.inTime)/1000;

      this.updataLookTime(look_time);
    });

    //关闭更新查看时长
    this.themeableBrowser.on("closePressed").subscribe(item=>{
      this.backTime=Date.parse(new Date().toString());
      let look_time=(this.backTime-this.inTime)/1000;

      this.updataLookTime(look_time);
    });
  }

  /**
   * 回写资源查看时长
   */
  updataLookTime(lookTime)
  {
    this.http.post("/exercise/updateLooktime.do",{studentId:this.studentId,sourceId:this.source_idStr,looktime:lookTime}).subscribe(item=>{
      if(item["Code"]=="11111111") {
        this.http.showToast(item["Message"], "bottom");
      }
    });
  }
}
